package com.kfm.servlet.day04;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;

@WebServlet("/time")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取 cookie
        Cookie[] cookies = req.getCookies();
        LocalDateTime now = LocalDateTime.now();
        for (Cookie cookie : cookies) {
            if ("lastTime".equals(cookie.getName())){
                // 获取上次访问时间
                String lastTime = cookie.getValue();
                lastTime = URLDecoder.decode(lastTime, "utf-8");
                // 设置响应数据
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write("欢迎回来，您上次访问时间为：" + lastTime);

                String encode = URLEncoder.encode(now.toString() + " " + "kfm", "utf-8");
                System.out.println(encode);
                // 更新 cookie
                cookie.setValue(encode);
                cookie.setMaxAge(60 * 60 * 24 * 30);
                resp.addCookie(cookie);
                return;
            }
        }

        // 设置响应数据
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write("欢迎您首次访问");
        // 创建 cookie
        String encode = URLEncoder.encode(now.toString() + " " + "kfm", "utf-8");
        Cookie cookie = new Cookie("lastTime", encode);
        cookie.setMaxAge(60 * 60 * 24 * 30);
        resp.addCookie(cookie);
    }

}
